package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.auth.StpKit;
import com.yupi.yupicturebackend.model.dto.user.UserLoginRequest;
import com.yupi.yupicturebackend.model.dto.user.UserQueryRequest;
import com.yupi.yupicturebackend.model.dto.user.UserRegisterRequest;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.UserRoleEnum;
import com.yupi.yupicturebackend.model.vo.LoginUserVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.UserService;
import com.yupi.yupicturebackend.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
* @author jiangzile
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-03-19 13:36:09
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @Override
    public Long userRegister(UserRegisterRequest userRegisterRequest) {
        //1,校验
        // 1）检查是否为null
        if (BeanUtil.isEmpty(userRegisterRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }

        //2),检查用户名长度，密码长度，两次密码是否一致
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        ThrowUtils.throwIf(userAccount.length() < 2,new BusinessException(ErrorCode.PARAMS_ERROR,"用户名长度不得小于2位"));
        ThrowUtils.throwIf(userPassword.length() < 4,new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度不得小于4位"));
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致"));

        //2，判断账号是否已经存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        ThrowUtils.throwIf(count > 0,new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在"));

        //3,密码加盐加密
        String encryptPassword = getEncryptPassword(userPassword);
        userRegisterRequest.setUserPassword(encryptPassword);

        //4,账号密码存入数据库
        User user = new User();
        BeanUtil.copyProperties(userRegisterRequest,user);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult,ErrorCode.SYSTEM_ERROR,"数据库错误");

        //5,返回用户id
        return user.getId();
    }

    /**
     * 用户登录
     * @param userLoginRequest
     * @param request
     * @return
     */
    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1,校验（前端传的数据是否为空，用户名和密码长度、账户是否存在）
        ThrowUtils.throwIf(userLoginRequest == null,ErrorCode.PARAMS_ERROR,"参数为空");

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        ThrowUtils.throwIf(userAccount.length() < 2,ErrorCode.PARAMS_ERROR,"用户名长度不得小于2位");
        ThrowUtils.throwIf(userPassword.length() < 4,ErrorCode.PARAMS_ERROR,"密码长度不得小于4位");

        //2,密码加密
        String encryptPassword = this.getEncryptPassword(userPassword);

        //3,检验账号、密码是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = this.getOne(queryWrapper);
        ThrowUtils.throwIf(user == null,ErrorCode.PARAMS_ERROR,"用户名或密码错误");

        //4,保存登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user);

        //5，保存用户登录态到Sa-Token当中，便于空间鉴权时候使用，注意保证该用户信息与SpringSession中信息的过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE, user);

        //5,返回脱敏登录信息
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //1,先判断是否已经登录
        User currentUser = (User)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null,ErrorCode.NOT_LOGIN_ERROR);

        //2,从数据库查，不要直接使用Session中的User对象
        // 万一在这期间，用户修改了个人信息，Session中存的数据跟数据库的数据不一致
        currentUser = this.getById(currentUser.getId());
        ThrowUtils.throwIf(currentUser == null,ErrorCode.NOT_LOGIN_ERROR);
        return currentUser;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    /*@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)*/
    public boolean userLogout(HttpServletRequest request) {
        //1,判读是否登录
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        ThrowUtils.throwIf(user == null,ErrorCode.NOT_LOGIN_ERROR);

        //2,移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取登录用户的脱敏信息
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        ThrowUtils.throwIf(user == null,ErrorCode.PARAMS_ERROR,"参数为空");
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user,loginUserVO);
        return loginUserVO;
    }

    /**
     * 用户密码进行md5加密
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        final String SALT = "yupi";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 根据 id 获取脱敏后的用户信息包装类
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        ThrowUtils.throwIf(user == null,ErrorCode.PARAMS_ERROR,"参数为空");
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }

    /**
     * 获取脱敏后的用户列表
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null){
            return new ArrayList<>();
        }
        return BeanUtil.copyToList(userList, UserVO.class);
    }

    /**
     * 获取分页查询条件的条件构造器
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            return new QueryWrapper<>();
        }

        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq(ObjUtil.isNotNull(id) && id > 0,"id",id)
                .eq(StrUtil.isNotBlank(userRole),"userRole",userRole)
                .like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount)
                .like(StrUtil.isNotBlank(userName), "userName", userName)
                .like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile)
                .orderBy(StrUtil.isNotBlank(sortField),sortOrder.equals("ascend"),sortField);
        return queryWrapper;
    }

    /**
     * 判断用户是否为管理员
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}




